package com.hbuzzs.shiro.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbuzzs.shiro.config.shiro.ShiroMD5;
import com.hbuzzs.shiro.entity.Role;
import com.hbuzzs.shiro.entity.UserInfo;
import com.hbuzzs.shiro.entity.UserRole;
import com.hbuzzs.shiro.entity.request.AddUserRequest;
import com.hbuzzs.shiro.mapper.RoleMapper;
import com.hbuzzs.shiro.mapper.UserInfoMapper;
import com.hbuzzs.shiro.mapper.UserRoleMapper;
import com.hbuzzs.shiro.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhangzhishun
 * @since 2020-09-22
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    private final UserInfoMapper userInfoMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insertUser(AddUserRequest request) {
        // 新用户信息
        UserInfo newUserInfo = UserInfo.builder()
                .userName(request.getUserName())
                // 使用昵称加盐加密
                .userPasswd(ShiroMD5.shiroMD5(request.getUserName(), request.getUserPasswd())).build();
        // 向user_info表插入数据
        userInfoMapper.insertUser(newUserInfo);
        // 查找角色名称对应角色ID
        List<Role> role = roleMapper.selectByMap(new HashMap<String, Object>(4) {{
            put("name", request.getRoleName());
        }});
        if (role.size() == 1) {
            // 插入用户-角色表
            userRoleMapper.insert(UserRole.builder()
                    .roleId(Integer.parseInt(role.get(0).getId().toString()))
                    .userId(newUserInfo.getUserId()).build());
            return newUserInfo.getUserId();
        } else if (role.size() == 0) {
            throw new RuntimeException("角色不存在");
        } else {
            throw new RuntimeException("该角色名称在系统有超过一个角色ID，无法插入");
        }
    }

    @Override
    public UserInfo getUserInfoByIdRole(Map<String, Object> principal) {
        return userInfoMapper.getUserInfoByIdRoleName(principal);
    }

}
